<template>
    <view class="uni-tab-bar">
		<!-- <text @click="goIndex">{{loadCategory}},{{loadList}},{{allItemData.length}}{{testDataKey}}</text> -->
        <scroll-view id="tab-bar" class="uni-swiper-tab" scroll-x :scroll-left="scrollLeft">
            <view v-for="(tab,index) in tabBars" :key="tab.categoryID" :class="['swiper-tab-list',tabIndex==index ? 'active' : '']"
                :id="tab.categoryID" :data-current="index" @tap="tapTab">{{tab.categoryName}}</view>
        </scroll-view>
        <swiper :current="tabIndex" class="swiper-box" duration="300" @change="changeTab">
            <swiper-item v-for="(itemData,index1) in allItemData" :key="index1">
                <scroll-view class="list" scroll-y @scrolltoupper="refresh(index1)" @scrolltolower="loadMore(index1)">
					<!-- <view class="uni-tab-bar-loading">
						<uni-refresh :refreshType="tabItemPages[index1].refreshType" :contentText="refreshText"></uni-refresh>
					</view> -->
					<block v-if="itemData != null && itemData.banners != null && itemData.banners.length > 0">
						<index-banner :data="itemData.banners" :resourceHostPic="resourceHostPic" @click="bannerClick(itemData)"></index-banner>
					</block>
                    <block v-if="itemData.articles != null && itemData.articles.length > 0">
						<block v-for="(article,index2) in itemData.articles" :key="index2">
						    <article-item class="media-list" :article="article.article" :author="article.author" :resourceHostPic="resourceHostPic" @clickAuthor="clickAuthor(article.author.authorID)" @close="close(index1,index2)" @clickItem="goDetail(article)">
							</article-item>
						</block>
						<view class="media-list-bottom-blank"></view>
						<view class="uni-tab-bar-loading" @click="loadMore()">
							<uni-load-more :loadingType="tabItemPages[index1].loadingType" :contentText="loadingText"></uni-load-more>
						</view>
					</block>
                    <block v-else>
						<view class="nodata-area">
							<text class="nodata-text">暂无数据</text>
						</view>
					</block>
                </scroll-view>
            </swiper-item>
        </swiper>
    </view>
</template>
<script>
	import indexBanner from '@/components/indexBanner.vue';
    import articleItem from '@/components/articleItem.vue';
	import uniRefresh from '@/components/uni-refresh.vue';
	import uniLoadMore from '@/components/uni-load-more.vue';
	import api from '../../common/api.js';
	var host = api.getHost;
	var resource = api.getResource;
	var category_api = api.getCategory;
	var list_api = api.getList;
	var FIRTST_LOAD = 0;
	var REFRESH = 1;
	var LOAD_MORE = 2;
	var CATEGORY_ID_PREFIX = "ID"
    export default {
        components: {
			indexBanner,
            articleItem,
			uniRefresh,
			uniLoadMore,
        },
        data() {
            return {
				refreshText: {
					contentdown: "下拉刷新数据",
					contentrefresh: "正在刷新...",
					contentnomore: "刷新完成"
				},
				loadingText: {
					contentdown: "上拉显示更多",
					contentrefresh: "正在加载...",
					contentnomore: "没有更多数据了"
				},
				loadCategory: '空',
				loadList: '空',
                scrollLeft: 0,
                isClickChange: false,
                tabIndex: 0,
				resourceHostPic: '',
                tabBars: [{
                    categoryName: '精选',
                    categoryID: 'jingxuan'
                }, {
                    categoryName: '好水果',
                    categoryID: 'haoshuiguo'
                }, {
                    categoryName: '其他',
                    categoryID: 'qita'
                }],
				tabItemPages:[],
				allItemData:[],
            }
        },
        created: function() {
			console.log('tabbar-faxian-onLoad')
			this.resourceHostPic = resource;
			this.getCategory()
        },
		onPullDownRefresh: function(){
			var position = this.tabIndex;
			console.log('tabbar-faxian-onPullDownRefresh position='+position)
			if(this.tabItemPages[position].loadingType == 1){
				console.log('refresh ======正在加载更多中，已经被过滤=======position=' + this.tabIndex);
				setTimeout(() => {
					uni.stopPullDownRefresh();
				}, 200);
			}else if(this.tabItemPages[position].refreshType == 1){
				console.log('refresh ======正在刷新数据中，已经被过滤=======position=' + this.tabIndex);
				setTimeout(() => {
					uni.stopPullDownRefresh();
				}, 200);
			}else{
				this.tabItemPages[position].refreshType = 1;
				this.tabItemPages[position].pageNum = 1;
				this.getListByCategoryWithPosition(position, this.tabBars[position].categoryID, this.tabItemPages[position].pageNum, REFRESH)
			}
		},
        methods: {
			getCategory(){
				uni.showLoading({
					title: '加载中'
				});
				let url = host + category_api;
				//let url = 'api/v1/discovery/channel/list';
				let that = this;
				uni.request({
					url: url,
					method: 'GET',
					header: {
					},
					success: (res) => {
						uni.hideLoading()
						that.loadCategory = 'success';
						that.tabBars = res.data.data;
						that.tabIndex = 0;
						console.log('getCategory success data=' + JSON.stringify(res.data));
						that.initAllItemData();
					},
					fail: (res) => {
						uni.hideLoading()
						that.loadCategory = 'fail';
						console.log('getCategory fail data=' + JSON.stringify(res.data));
					}
				});
			},
			initAllItemData(){
				if(this.tabBars != null && this.tabBars.length > 0){
					for(var i = 0; i < this.tabBars.length; i++){
						var o = {"refreshType": -1,"loadingType": 0,"pageNum":1,"hasNextPage":'N'}
						this.tabItemPages.push(o);
						this.tabBars[i].categoryID = CATEGORY_ID_PREFIX + this.tabBars[i].categoryID;
						this.allItemData.push({
							"banners": [],
							"articles": [],
						});
					}
					this.getListByCategoryWithPosition(this.tabIndex, this.tabBars[this.tabIndex].categoryID, 1, FIRTST_LOAD);
				}
			},
			getListByCategoryWithPosition(position, _categoryID, pageNum, time){
				if(time === FIRTST_LOAD){
					uni.showLoading({
						title: '加载中'
					});
				}
				let categoryID = _categoryID;
				if(_categoryID.indexOf(CATEGORY_ID_PREFIX) != -1){
					categoryID = _categoryID.replace(CATEGORY_ID_PREFIX,"");
				}
				console.log('getListByCategoryWithPosition position=' + position + ' _categoryID='+ _categoryID + ' categoryID='+ categoryID + ' pageNum='+ pageNum);
				this.loadList = 'start';
				 
				let url = host + list_api;
				let that = this;
				let pageSize = 10;
				uni.request({
					url: url,
					method: 'POST',
					header: {
						'content-type': 'application/json'
					},
					data: {
						categoryID: categoryID,
						customerID: '-1',
						pageNum: pageNum,
						pageSize: pageSize
					},
					success: (res) => {
						that.loadList = 'success';
						let data = res.data.data;
						that.tabItemPages[position].hasNextPage = data.hasNextPage;
						if('N' == data.hasNextPage){
							that.tabItemPages[position].loadingType = 2
						}else{
							that.tabItemPages[position].loadingType = 0;
						}		
							
						if(time == FIRTST_LOAD){
							that.tabItemPages[position].pageNum = 2;
							//that.allItemData.splice(position, 0, data);
							that.allItemData[position].banners = data.banners;
							that.allItemData[position].articles = data.articles;
						}else if(time == REFRESH){
							that.tabItemPages[position].pageNum = 2;
							that.allItemData[position].banners = data.banners;
							that.allItemData[position].articles = data.articles;
							
							that.tabItemPages[position].refreshType = 2;
							setTimeout(() => {
								this.tabItemPages[position].refreshType = -1;
							}, 200);
						}else if(time == LOAD_MORE){
							that.tabItemPages[position].pageNum = pageNum+1
							if(data.articles != null && data.articles.length > 0){
								//push每次只能放一个数据，不能放一个列表
								//that.allItemData[position].articles.push(data.articles);
								that.allItemData[position].articles = that.allItemData[position].articles.concat(data.articles);
							}
						}
						
						//console.log('getListByCategoryWithPosition success position=' + position + ' data=' + JSON.stringify(res.data));
						console.log('getListByCategoryWithPosition success position=' + position + ' pageNum=' + pageNum + ' hasNextPage=' + data.hasNextPage
							+ ' banners=' + data.banners.length + ' articles=' + data.articles.length);
					},
					fail: (res) => {
						that.tabItemPages[position].refreshType = 0;
						that.tabItemPages[position].loadingType = 0;
						that.loadList = 'fail';
						console.log('getListByCategoryWithPosition fail data=' + JSON.stringify(res.data));
					},
					complete: () => {
						if(time === FIRTST_LOAD){
							uni.hideLoading()
						}else if(time == REFRESH){
							uni.stopPullDownRefresh()
						}
					}
				});
			},
            goDetail(e) {
				uni.navigateTo({
                    url: '/pages/detail/detail?data='+e.article.articleID
                })
            },
			clickAuthor(authorID) {
				uni.navigateTo({
				    url: '/pages/author/author?data='+authorID
				})
			},
			goIndex(){
				uni.navigateTo({
				    url: '/pages/index/index'
				})
			},
			refresh(e){
				console.log('refresh tabIndex=' + this.tabIndex);
				//用这个回调没有动画效果，应该用系统的page级别的下拉刷新
				/* var position = this.tabIndex;
				if(this.tabItemPages[position].loadingType == 1){
					console.log('refresh ======正在加载更多中，已经被过滤=======position=' + this.tabIndex);
				}else if(this.tabItemPages[position].refreshType == 1){
					console.log('refresh ======正在刷新数据中，已经被过滤=======position=' + this.tabIndex);
				}else{
					this.tabItemPages[position].refreshType = 1;
					setTimeout(() => {
						this.tabItemPages[position].pageNum = 1;
						this.getListByCategoryWithPosition(position, this.tabBars[position].categoryID, this.tabItemPages[position].pageNum, REFRESH)
					}, 500);
				}*/
			},
            loadMore(e) {
				console.log('loadMore tabIndex=' + this.tabIndex);
				var position = this.tabIndex;
				console.log('loadMore this.tabItemPages[position].hasNextPage=' + this.tabItemPages[position].hasNextPage);
				if('Y' == this.tabItemPages[position].hasNextPage){
					console.log('loadMore this.tabItemPages[position].loadingType=' + this.tabItemPages[position].loadingType);
					if(this.tabItemPages[position].refreshType == 1){
						console.log('loadMore ======正在刷新中，已经被过滤=======position=' + position);
					}else if(this.tabItemPages[position].loadingType == 1){
						console.log('loadMore ======正在加载中，已经被过滤=======position=' + position);
					}else{
						this.tabItemPages[position].loadingType = 1;
						this.getListByCategoryWithPosition(position, this.tabBars[position].categoryID, this.tabItemPages[position].pageNum, LOAD_MORE)
						/* setTimeout(() => {
							this.getListByCategoryWithPosition(position, this.tabBars[position].categoryID, this.tabItemPages[position].pageNum, LOAD_MORE)
						}, 500); */
					}
				}
            },
            async changeTab(e) {
                let index = e.target.current;
				console.log("changeTab this.tabIndex="+this.tabIndex)
				console.log("changeTab index="+index)
				console.log("changeTab this.isClickChange="+this.isClickChange)
                if (this.isClickChange) {
					console.log("changeTab i am in")
                    this.tabIndex = index;
                    this.isClickChange = false;
                    return;
                }
                let tabBar = await this.getElSize("tab-bar"),
                    tabBarScrollLeft = tabBar.scrollLeft;
                let width = 0;

                for (let i = 0; i < index; i++) {
                    let result = await this.getElSize(this.tabBars[i].categoryID);
                    width += result.width;
                }
				console.log("changeTab width="+width)
                let winWidth = uni.getSystemInfoSync().windowWidth,
                    nowElement = await this.getElSize(this.tabBars[index].categoryID),
                    nowWidth = nowElement.width;
                if (width + nowWidth - tabBarScrollLeft > winWidth) {
                    this.scrollLeft = width + nowWidth - winWidth;
                }
                if (width < tabBarScrollLeft) {
                    this.scrollLeft = width;
                }
                this.isClickChange = false;
                this.tabIndex = index; //一旦访问data就会出问题
				
				if(this.allItemData[this.tabIndex].articles.length == 0){
					console.log("changeTab, i am auto load");
					this.getListByCategoryWithPosition(this.tabIndex, this.tabBars[this.tabIndex].categoryID, 1, FIRTST_LOAD);
				}
            },
            getElSize(id) { //得到元素的size
				console.log("getElSize this.tabIndex="+this.tabIndex + " id="+id)
                return new Promise((res, rej) => {
                    uni.createSelectorQuery().select("#" + id).fields({
                        size: true,
                        scrollOffset: true
                    }, (data) => {
                        res(data);
                    }).exec();
                })
            },
            async tapTab(e) { //点击tab-bar
				console.log("tapTab this.tabIndex="+this.tabIndex + " e.target.dataset.current="+e.target.dataset.current)
                if (this.tabIndex === e.target.dataset.current) {
                    return false;
                } else {
                    let tabBar = await this.getElSize("tab-bar"),
                        tabBarScrollLeft = tabBar.scrollLeft; //点击的时候记录并设置scrollLeft
                    this.scrollLeft = tabBarScrollLeft;
                    this.isClickChange = true;
                    this.tabIndex = e.target.dataset.current
                }
				
				if(this.allItemData[this.tabIndex].articles.length == 0){
					console.log("tapTab, i am auto load");
					this.getListByCategoryWithPosition(this.tabIndex, this.tabBars[this.tabIndex].categoryID, 1, FIRTST_LOAD);
				}
            }
        }
    }
</script>

<style>
	.uni-swiper-tab::-webkit-scrollbar {
       width: 0;
       height: 0;
       color: transparent;
	}
	.uni-swiper-tab::-webkit-scrollbar { 
		width: 0 !important }
	:-webkit-scrollbar { 
		width: 0;
		height: 0;
		color: transparent;
	}
	.uni-tab-bar{
		width: 750upx;
		background-color: #f5f5f5 ;
	}
	.uni-swiper-tab{
		width: 750upx;
	}
	.swiper-tab-list{
		min-width: 80upx;
		max-width: 150upx;
		height: 100upx;
		line-height: 100upx;
		margin-left: 10upx;
		margin-right: 10upx;
		display: inline-block;
	    white-space: nowrap; 
	    overflow: hidden;
	    text-overflow:ellipsis;
	}
	.swiper-box{
		width: 750upx;
	}
	.media-list{
		width: 750upx;
		background-color: #f5f5f5 ;
	}
	.media-list-bottom-blank{
		width: 750upx;
		height: 25upx;
		background-color: #f5f5f5 ;
	}
	.nodata-area{
		width: 750upx;
		height: 500upx;
		padding-top: 200upx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.nodata-text{
		font-size: 28upx;
		color: #999999;
	}
	 
</style>